package com.ju;

import java.util.Arrays;

/**
 * @description 获取雨量
 * @author wj
 * @date 2025-03-17
 */
public class RainColumnArrayPeriodSize {

  public static void main(String[] args) {
    int[] arr = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
    System.out.println(getPeriodSize(arr));
  }


  /**
   * 获取数组的周期性长度
   * @param arr 数组
   * @return int
   */
  private static int getPeriodSize(int[] arr) {
    if (arr == null || arr.length == 0 || Arrays.stream(arr).allMatch(el -> el <= 0)) {
      return 0;
    }
    int endIndex = arr.length;
    int[] newArr = Arrays.copyOf(arr, endIndex);
    int maxInt = 1;
    int sum = 0;
    int loopNum = 0;
    do {
      int first = 0;
      int firstIndex = 0;
      int tempIndex = 0;
      int elMoreThanZeroNum = 0;
      int[] tempArr = new int[newArr.length];
      for (int i = 0; i < newArr.length; i++) {
        int el = newArr[i];
        if (el > 0) {
          if (el > maxInt) {
            maxInt = el;
          }
          if (first == 0) {
            first = el;
            firstIndex = i;
          } else {
            endIndex = i;
            int periodSize = i - tempIndex - 1;
            if (periodSize > 0){
              sum += periodSize;
            }
          }
          tempIndex = i;
        }
        if (--el > 0) {
          elMoreThanZeroNum++;
        }
        tempArr[i] = el;
      }
      if (elMoreThanZeroNum <= 1) {
        // 新数组大于1的元素个数小于等于1，直接返回，不再遍历
        return sum;
      }
      newArr = Arrays.copyOfRange(tempArr, firstIndex, endIndex);
      loopNum++;
    } while (loopNum < maxInt);
    return sum;
  }


}
